package com.example.exjnidemo.exbluetooth01.socketclient;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.AsyncTask;
import android.util.Log;
import com.example.exjnidemo.exbluetooth01.i.CallBack;
import com.example.exjnidemo.exbluetooth01.i.ConstantUtils;
import com.example.exjnidemo.exbluetooth01.m.YXJBluetoothManager;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Random;
import java.util.UUID;


public class ClientBluetoothSocketUtil {

    private BluetoothDevice serverDevice;
    private BluetoothSocket socket =null;

    /**
     * @param d
     * @throws IOException
     */
    public ClientBluetoothSocketUtil(BluetoothDevice d) throws IOException {
        /**获取远端蓝牙配置BluetoothDevice*/
        serverDevice = YXJBluetoothManager.getInstance().getRemoteDevice(d.getAddress());
        /**获取客户端通信BluetoothSocket  SPP_UUID一定需要和服务端一致 */
        socket = serverDevice.createRfcommSocketToServiceRecord(UUID.fromString(ConstantUtils.SPP_UUID));
    }



    /**
     * 开始连接
     *
     * @param callBack
     */
    public void startConnect(CallBack callBack){
        new Thread(new Runnable() {

            @Override
            public void run() {
                    if (serverDevice == null){
                        if (callBack!=null)
                            callBack.onError(-1,"蓝牙还未配对");
                        return;
                    }

                    if (socket!=null){
                        try {
                            // Connect the device through the socket. This will block
                            // until it succeeds or throws an exception
                            socket.connect();
                        } catch (IOException connectException) {
                            // Unable to connect; close the socket and get out
                            try {
                                Method m = serverDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
                                socket = (BluetoothSocket) m.invoke(serverDevice, 1);
                                socket.connect();
                            } catch (Exception e) {
                                if (callBack!=null) callBack.onError(-1,"连接失败！");
                                try{
                                    socket.close();
                                }catch (IOException ie){
                                    ie.printStackTrace();
                                }
                            }
                            return;
                        }
                    }else {
                        if (callBack!=null)
                            callBack.onError(-1,"获取socket失败！");
                        return;
                    }


                    if (!socket.isConnected()){
                        if (callBack!=null) callBack.onError(-1,"连接失败！");
                        return;
                    }

                    /**
                     * 发送信息
                     */
                    try {
                        sendMsgToServer(socket,callBack);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }).start();
    }


    /**
     * 发送信息给服务端
     *
     * @param socket
     * @param callBack
     * @throws IOException
     */
    private void sendMsgToServer(BluetoothSocket socket, CallBack callBack) throws IOException {
        OutputStream outputStream = socket.getOutputStream() ;
        if (outputStream!=null){
            if (YXJBluetoothManager.getInstance().isDiscovering()){
                YXJBluetoothManager.getInstance().cancelDiscovery();
            }

            outputStream.write((""+new Random().nextInt(100)).getBytes("utf-8"));
            if (callBack !=null){
                callBack.onResult("传输成功！");
            }
        }else {
            if (callBack !=null){
                callBack.onError(-1,"传输失败！");
            }
        }
    }


    /**
     * 读取  蓝牙连接通信数据
     *
     */
    public class readSocketTask extends AsyncTask<BluetoothSocket, Void, String> {

        @Override
        protected String doInBackground(BluetoothSocket... bluetoothSockets) {
            BluetoothSocket s = bluetoothSockets[0];
            try {
                BufferedInputStream in = new BufferedInputStream(s.getInputStream());
                byte[] bytes=new byte[1024];
                int len;
                String result;
                while ((len=in.read()) != -1){
                    in.read(bytes,0,len);
                }
                result = new String(bytes);
                in.close();
                return result ;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.v("=====read=====",""+s);
        }
    }
}
